<template>
  <div class="product-management">
    <!-- 页面标题 -->
    <PageHeader 
      title="产品管理" 
      description="管理您的产品信息，进行批量导入/导出、数据清洗等数据维护操作"
      icon="Goods"
    />
    
    <!-- 添加提示信息 -->
    <div class="data-management-tip" v-if="showDataManagementTip">
      <el-alert
        title="提示：此页面用于批量数据维护。如需进行日常业务操作，请前往【库存管理 → 产品管理】"
        type="info"
        show-icon
        closable
        @close="handleTipClose"
      >
        <template #default>
          <div class="tip-content">
            <span>提示：此页面用于批量数据维护。如需进行日常业务操作，请前往</span>
            <el-link type="primary" @click="goToInventoryManagement">库存管理 → 产品管理</el-link>
          </div>
        </template>
      </el-alert>
    </div>
    
    <!-- 智能洞察 -->
    <SmartInsights 
      v-if="stats && Object.keys(stats).length > 0"
      :insights="smartInsights"
      @action="handleInsightAction"
    />
    
    <!-- 产品统计 -->
    <ProductStats 
      :stats="stats"
      :loading="loading"
    />
    
    <!-- 功能区域 -->
    <el-card class="function-area" shadow="never">
      <el-row :gutter="20">
        <el-col :span="16">
          <ProductFilter 
            :query-params="queryParams"
            @search="handleSearch"
            @reset="handleReset"
          />
        </el-col>
        <el-col :span="8">
          <div class="function-buttons">
            <el-dropdown trigger="click" @command="handleBatchCommand">
              <el-button class="batch-btn">
                批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="export">导出产品</el-dropdown-item>
                  <el-dropdown-item command="import">导入产品</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除产品</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 产品表格 -->
    <ProductTable
      :table-data="products"
      :loading="loading"
      :view-mode="'table'"
      :pagination="pagination"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @sort-change="handleSortChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @command="handleTableCommand"
    />
    
    <!-- 新增产品抽屉 -->
    <ProductEditDrawer
      v-model="addDrawerVisible"
      :mode="'create'"
      :product-data="null"
      @submit="createProduct"
      @close="handleAddDrawerClose"
    />
    
    <!-- 编辑产品抽屉 -->
    <ProductEditDrawer
      v-model="editDrawerVisible"
      :mode="'edit'"
      :product-data="editingProduct"
      @submit="updateProduct"
      @close="handleEditDrawerClose"
    />
    
    <!-- 产品详情抽屉 -->
    <ProductDetailDrawer
      v-model="detailDrawerVisible"
      :product-id="detailProduct?.id || null"
      @edit="handleEditProduct"
      @close="handleDetailDrawerClose"
    />
    
    <!-- 产品导入向导 -->
    <ProductImportWizard
      v-model="importWizardVisible"
      :mode="'import'"
      :filter-params="queryParams"
      @import-success="handleImportSuccess"
    />
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, reactive, computed, onMounted } from '@vue/runtime-core'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Goods, Plus, ArrowDown, Upload, Download, Delete 
} from '@element-plus/icons-vue'
import * as productAPI from '@/api/inventory'
import { getProductStats } from '@/api/inventory'
import type { Product } from '@/types/product'

// 使用路由
const router = useRouter()

// 导入组件
import PageHeader from '@/components/layout/PageHeader.vue'
import SmartInsights from '@/components/insights/SmartInsights.vue'
import ProductStats from '@/views/inventory/components/ProductStats.vue'
import ProductFilter from '@/views/inventory/components/ProductFilter.vue'
import ProductTable from '@/views/inventory/components/ProductTable.vue'
import ProductEditDrawer from '@/components/inventory/ProductFormDialog.vue'
import ProductDetailDrawer from '@/components/inventory/ProductDetailDrawer.vue'
import ProductImportWizard from '@/components/inventory/ProductImportExport.vue'

interface ProductQueryParams {
  name: string
  sku: string
  status: string
  categoryId: number | null
  brandId: number | null
  minStock?: number
  maxStock?: number
  minPrice?: number
  maxPrice?: number
  page: number
  limit: number
}

interface ProductStats {
  totalProducts: number
  activeProducts: number
  lowStockProducts: number
  outOfStockProducts: number
  productTrend: number
  activeTrend: number
  lowStockTrend: number
}

// 控制提示信息显示
const showDataManagementTip = ref(true)

// 跳转到库存管理
const goToInventoryManagement = () => {
  router.push('/inventory/products')
}

// 关闭提示信息
const handleTipClose = () => {
  showDataManagementTip.value = false
}

// 响应式数据
const products = ref<Product[]>([])
const loading = ref(false)
const addDrawerVisible = ref(false)
const editDrawerVisible = ref(false)
const detailDrawerVisible = ref(false)
const importWizardVisible = ref(false)
const detailProduct = ref<Product | null>(null)
const editingProduct = ref<Product | null>(null)
const selectedProducts = ref<Product[]>([])
const stats = ref<ProductStats>({
  totalProducts: 0,
  activeProducts: 0,
  lowStockProducts: 0,
  outOfStockProducts: 0,
  productTrend: 0,
  activeTrend: 0,
  lowStockTrend: 0
})

const smartInsights = ref([
  {
    id: '1',
    type: 'opportunity',
    title: '热销产品分析',
    description: '本月新增3个热销产品，库存周转率提升15%',
    priority: 'high',
    products: [],
    confidence: 85,
    action: () => ElMessage.info('查看热销产品详情')
  },
  {
    id: '2',
    type: 'risk',
    title: '库存风险预警',
    description: '5个产品库存不足，建议及时补货',
    priority: 'high',
    products: [],
    confidence: 78,
    action: () => ElMessage.info('查看库存风险产品')
  }
])

const queryParams = reactive<ProductQueryParams>({
  name: '',
  sku: '',
  status: '',
  categoryId: null,
  brandId: null,
  page: 1,
  limit: 20
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 计算属性
const activeProducts = computed(() => {
  return products.value.filter(product => product.status === 1)
})

// 生命周期钩子
onMounted(() => {
  loadProducts()
  loadStats()
})

// 方法
const loadProducts = async () => {
  loading.value = true
  try {
    const response = await productAPI.getProducts({
      ...queryParams,
      page: pagination.page,
      limit: pagination.limit
    })
    
    if (response.success) {
      products.value = response.data.list
      pagination.total = response.data.pagination.total
    } else {
      ElMessage.error(response.message || '获取产品列表失败')
    }
  } catch (error) {
    ElMessage.error('获取产品列表失败')
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await getProductStats()
    if (response.success) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('获取产品统计失败:', error)
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadProducts()
}

const handleReset = () => {
  Object.assign(queryParams, {
    name: '',
    sku: '',
    status: '',
    categoryId: null,
    brandId: null,
    minStock: undefined,
    maxStock: undefined,
    minPrice: undefined,
    maxPrice: undefined
  })
  pagination.page = 1
  loadProducts()
}

const handleSelectionChange = (selection: Product[]) => {
  selectedProducts.value = selection
}

const handleRowClick = (row: Product) => {
  showDetailDrawer(row)
}

const handleSortChange = (sort: { column: any, prop: string, order: string }) => {
  // 处理排序逻辑
  loadProducts()
}

const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  loadProducts()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadProducts()
}

const handleTableCommand = (command: { action: string, row: Product }) => {
  const { action, row } = command
  switch (action) {
    case 'detail':
      showDetailDrawer(row)
      break
    case 'edit':
      showEditDrawer(row)
      break
    case 'orders':
      viewProductOrders(row)
      break
    case 'delete':
      deleteProduct(row)
      break
  }
}

const showAddDrawer = () => {
  addDrawerVisible.value = true
}

const showEditDrawer = (product: Product) => {
  editingProduct.value = product
  editDrawerVisible.value = true
}

const showDetailDrawer = (product: Product) => {
  detailProduct.value = product
  detailDrawerVisible.value = true
}

const handleEditProduct = (product: Product) => {
  detailDrawerVisible.value = false
  showEditDrawer(product)
}

const viewProductOrders = (product: Product) => {
  // 跳转到产品订单页面
  ElMessage.info(`查看产品 ${product.name} 的订单`)
}

const deleteProduct = async (product: Product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品 "${product.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        type: 'warning'
      }
    )
    
    const response = await productAPI.deleteProduct(product.id)
    if (response.success) {
      ElMessage.success('产品删除成功')
      loadProducts()
    } else {
      ElMessage.error(response.message || '删除产品失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除产品失败')
    }
  }
}

const createProduct = async (productData: Product) => {
  try {
    const response = await productAPI.createProduct(productData)
    if (response.success) {
      ElMessage.success('产品创建成功')
      addDrawerVisible.value = false
      loadProducts()
      loadStats()
    } else {
      ElMessage.error(response.message || '创建产品失败')
    }
  } catch (error) {
    ElMessage.error('创建产品失败')
  }
}

const updateProduct = async (productData: Product) => {
  try {
    const response = await productAPI.updateProduct(productData.id, productData)
    if (response.success) {
      ElMessage.success('产品更新成功')
      editDrawerVisible.value = false
      loadProducts()
    } else {
      ElMessage.error(response.message || '更新产品失败')
    }
  } catch (error) {
    ElMessage.error('更新产品失败')
  }
}

const handleBatchCommand = (command: string) => {
  switch (command) {
    case 'export':
      exportProducts()
      break
    case 'import':
      importWizardVisible.value = true
      break
    case 'delete':
      batchDeleteProducts()
      break
  }
}

const exportProducts = () => {
  ElMessage.info('导出产品功能开发中')
}

const batchDeleteProducts = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请先选择要删除的产品')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedProducts.value.length} 个产品吗？此操作不可恢复。`,
      '批量删除确认',
      {
        type: 'warning'
      }
    )
    
    const ids = selectedProducts.value.map(product => product.id)
    const response = await productAPI.batchDeleteProducts(ids)
    if (response.success) {
      ElMessage.success('批量删除产品成功')
      loadProducts()
      loadStats()
    } else {
      ElMessage.error(response.message || '批量删除产品失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除产品失败')
    }
  }
}

const handleAddDrawerClose = () => {
  addDrawerVisible.value = false
}

const handleEditDrawerClose = () => {
  editDrawerVisible.value = false
  editingProduct.value = null
}

const handleDetailDrawerClose = () => {
  detailDrawerVisible.value = false
  detailProduct.value = null
}

const handleImportSuccess = () => {
  importWizardVisible.value = false
  loadProducts()
  loadStats()
}

const handleInsightAction = (insight: any) => {
  insight.action()
}
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.function-area {
  margin: 20px 0;
  border-radius: 8px;
}

.function-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  align-items: center;
  height: 100%;
}

.add-btn {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.add-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.batch-btn {
  border-color: #dcdfe6;
  color: #606266;
}

.batch-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-management {
    padding: 10px;
  }
  
  .function-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .add-btn,
  .batch-btn {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>